/*
 * 消息管理 http.js
 * @Author: Ray
 * @Date:   2018-01-31
 */
;
(function(window) {
    'use strict';

    var hooks = {};

    var $ui = {
        showToast : function (msg, location) {
            api.toast({
                msg: msg,
                duration: 2000,
                location: location || 'middle'
            })
        },
        showLoading : function (title) {
            api.showProgress({
                style: 'default',
                animationType: 'fade',
                title: title || '',
                text: '请稍后...',
            })
        }
    }

    if (window._env === 'prod') {
        //线上接口地址
        hooks.passUrl = 'https://passport.dding.net/';
        hooks.saasUrl = 'https://manageapi.dding.net/v3/';
    } else {
        //线下接口地址
        hooks.passUrl = 'http://dev-gate.dding.net:7080/'; //线下pass
        // hooks.saasUrl = 'http://qa-saas.dding.net:7012/v3/'; //研发同学使用的
        // hooks.saasUrl = 'http://qa-saas.dding.net:7002/v3/'; //测试同学使用的
        hooks.saasUrl = 'https://saas-manage-test.dding.net/v3/'; //有api网关地址
    }

    //http请求方式
    hooks.methods = {
        DELETE: 'delete',
        GET: 'get',
        POST: 'post',
        PUT: 'put'
    };

    //需要在body参数中加入token的api
    hooks.bodyNeedTokenApis = [
        'passwd1',
        'passwd2',
        'change_pw1',
        'change_pw2',
        'api/edit_nickname'
    ];

    /**
     * 填充api
     * @param {String} apiPath
     * @param {Object} routeParams 路由参数
     */
    hooks.fillApi = function(apiPath, routeParams) {
        var apiPathOri = apiPath,
            apiPathArr = apiPath.split('/'),
            patt = /:/;

        if (!patt.test(apiPath)) {
            return apiPath;
        }

        if (!routeParams || !routeParams.length) {
            $ui.showToast('缺少api参数');
            return null;
        }

        if (routeParams && routeParams.length) {
            for (var i in apiPathArr) {
                if (patt.test(apiPathArr[i])) {
                    if (!routeParams.length) {
                        $ui.showToast('缺少api参数');
                        return null;
                    }

                    apiPathArr[i] = routeParams.shift();
                }
            }
        }

        return apiPathArr.join('/');
    };

    /**
     * 格式化参数
     * @param {Object} params 参数
     */
    hooks.formatParams = function(params) {
        var item;
        for (var i in params) {
            item = params[i];
            if (item != 0 && !item) {
                delete params[i];
            }

            if ($util.isArray(item) && !item.length) {
                delete params[i];
            }

            if (!!item && typeof item == 'object') {
                hooks.formatParams(item);
            }
        }
    };

    /**
     * 拼接http请求参数
     * @param {Object} data 请求参数
     */
    hooks.concatParams = function(data) {
        var params = '';
        if ($util.isJson(data)) {
            for (var key in data) {
                var value = data[key];
                if (value != '' || value != "") {
                    params += key + '=' + value + '&';
                }
            }
            params = params.substring(0, params.lastIndexOf('&'));
            params = encodeURI(params);
        }
        return params;
    };

    
    /**
     * 消息请求
     * @param {Object} apiObj api对象
     * @param {Object} routeParams 路由参数
     * @param {Object} params 普通参数
     * @param {Bool} isHideLoading 是否隐藏加载动画
     * @param {Bool} isHideErrMsg 是否隐藏错误提示
     */
    hooks.req = function(apiObj, routeParams, params, isHideLoading, isHideErrMsg, isPassApi) {
        var accessToken = $store.getAccessToken();
        var valueData = {}

        params = params || {};
        hooks.formatParams(params);

        if (hooks.bodyNeedTokenApis.indexOf(apiObj.path) >= 0) {
            params.access_token = accessToken;
        }

        !isHideLoading && $ui.showLoading();

        var apiPath = hooks.fillApi(apiObj.path, routeParams);
        if (!apiPath) {
            return;
        }
        
        var baseUrl = !isPassApi ? this.saasUrl : this.passUrl; 
        var fullPath = baseUrl + apiPath;
        
        $util.log('[http ==>' + apiObj.method + ']', fullPath, 'params:', params);

        if (apiObj.method == hooks.methods.GET || apiObj.method == hooks.methods.DELETE) {
            fullPath = fullPath + '?' + hooks.concatParams(params);
        } else {
            valueData = {
                body: params
            };
        }
        
        return new Promise(function (resolve,reject) {
            api.ajax({
                url: fullPath,
                method: apiObj.method,
                timeout: 10,
                encode: false,
                charset: 'utf-8',
                headers: {
                    'X-Access-Token': accessToken,
                    "YD-App": "ydapp_az",
                    "Content-Type": "application/json"
                },
                dataType: "json",
                data: {
                    "body": JSON.stringify(params)
                }
            }, function(ret, err) {
                api.refreshHeaderLoadDone();
                api.hideProgress();
    
                $util.logWarn('[http <==' + apiObj.method + ']', apiPath, 'ret:', ret, 'err:', err);
    
                if (err && err.body && $util.isObject(err.body)) {
                    err = err.body;
    
                    if (err.err_code !== 5006 && !isHideErrMsg) {
                        $ui.showToast(err.err_msg);
                    }
    
                    if (err.err_code == 401002) {
                        hooks.logout(2000);
                    } 
                    resolve({
                        res: null,
                        err: err.err_msg
                    });
                }
    
                if (err && err.msg && !isHideErrMsg) {
                    $ui.showToast(err.msg);
                    resolve({
                        res: null,
                        err: err.msg
                    });
                }
    
                if (ret && !isHideErrMsg) {
                    if (ret.ErrNo) {
                        $ui.showToast(ret.ErrMsg);
                    } else if (ret.err_code) {
                        $ui.showToast(ret.err_msg);
                    }
                }
    
                resolve({
                    res: ret && ret.result ? ret.result : ret,
                    err: err
                });   
            });
            
        })
        
    };

    /**
     * 退出
     * @param {Number} delay 延迟时间
     */
    hooks.logout = function(delay) {
        delay = delay || 0;
        api.refreshHeaderLoadDone();

        $store.setAccessToken(null);
        $store.setUserData(null);

        if (delay) {
            setTimeout(function() {
                api.rebootApp();
            }, delay);
        } else {
            api.rebootApp();
        }
    };

    //关闭所有窗口到login
    hooks.closeToLogin = function() {
        api.closeToWin({
            name: 'login',
            animation: {
                type: "fade", //动画类型（详见动画类型常量）
                subType: "from_right", //动画子类型（详见动画子类型常量）
                duration: 500 //动画过渡时间，默认300毫秒
            }
        });
    };

    window.$http = hooks;

})(window);